//
//  TKYFindTreeView.m
//  StationHouseHelper
//
//  Created by apple on 2018/5/8.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYFindTreeView.h"
#import <Foundation/Foundation.h>
@interface TKYFindTreeView()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *findTreeTableV;
@property (weak, nonatomic) IBOutlet UIView *choseView;
@property (nonatomic, strong) NSMutableArray *dataSourceArr;
@property (weak, nonatomic) IBOutlet UIButton *tureButton;
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;

@property (nonatomic, strong) TKYFindTreeModel *findTreeModel;
@property (nonatomic, assign) NSInteger row;
@end
@implementation TKYFindTreeView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        self = [[NSBundle mainBundle] loadNibNamed:@"TKYFindTreeView" owner:nil options:nil].lastObject;
        self.frame = frame;
        self.findTreeTableV.delegate = self;
        self.findTreeTableV.dataSource = self;
        self.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBgViewEvent)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        [self requestDataWithID:nil];
        [self.choseView tky_cornerWithRadius:10 borderColor:nil borderWidth:0];
        [self.findTreeTableV tky_cornerWithRadius:10 borderColor:nil borderWidth:0];

    }
    return self;
}



- (NSMutableArray *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"TKYFindTreeViewCell";
    TKYFindTreeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[TKYFindTreeViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    cell.findTreeModel = self.dataSourceArr[indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%@",self.nextResponder);
    NSLog(@"%ld",indexPath. row);
    NSInteger row = indexPath.row;
    for (TKYFindTreeModel *findTreeModel in self.dataSourceArr) {
            findTreeModel.isSelected = NO;
    }
    TKYFindTreeModel *model = _dataSourceArr[row];
    model.isSelected = YES;
    if (model.isOpen) {
        //原来是展开的，现在要收起,则删除model.detailArray存储的数据
        [self deleteObjectWithDataArray:model.detailArray count:0];
    }
    else {
        if (model.isParent == YES) {
            //原来是收起的，现在要展开，则需要将同层次展开的收起，然后再展开
            [self compareSameLevelWithModel:model row:row];
        }
        else {
            //点击的是最后一层数据，跳转到别的界面
//            if (self.selectedfindTreeModelBlock) {
//                self.selectedfindTreeModelBlock(model);
//            }
            // self.selectedBlock(model);
            //[self dismissViewControllerAnimated:YES completion:nil];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:model.name preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            }]];

            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                self.selectedfindTreeModelBlock(model);
                [self removeFromSuperview];
            }]];
            [[self LX_GetCurrentViewController] presentViewController:alert animated:YES completion:nil];
        }
    }
    
    model.isOpen = !model.isOpen;
    
    //滑动到屏幕顶部
    for (int i = 0; i < _dataSourceArr.count; i++) {
        TKYFindTreeModel *openModel = _dataSourceArr[i];
        
        if (openModel.isOpen && openModel.lv == 0) {
            //将点击的cell滑动到屏幕顶部
            NSIndexPath *selectedPath = [NSIndexPath indexPathForRow:i inSection:0];
            [tableView scrollToRowAtIndexPath:selectedPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }
    
    
    [tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

- (void)requestDataWithID:(NSString *)ids {
    
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&id=%@",kApiBaseUrl,kFindTreeUrl,str,ids];
    
    //第一
    [SVProgressHUD show];
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        if ([response[@"code"]integerValue] == 0) {
            NSArray *arr = response[@"flowSectionEntities"];
            
            
            if (self.findTreeModel) {
                self.findTreeModel.detailArray = [NSMutableArray array];
                for (NSDictionary * dic in arr) {
                    //TKYFindTreeModel *model = [TKYFindTreeModel new];
                    TKYFindTreeModel *model =  [TKYFindTreeModel mj_objectWithKeyValues:dic];
                    model.isOpen = NO;
                    [self.findTreeModel.detailArray addObject:model];
                }
                [self addObjectWithDataArray:self.findTreeModel.detailArray row:self.row + 1];
            } else {
                for (NSDictionary * dic in arr) {
                    // TKYFindTreeModel *model = [TKYFindTreeModel new];
                    TKYFindTreeModel *model=  [TKYFindTreeModel mj_objectWithKeyValues:dic];
                    model.isOpen = NO;
                    [self.dataSourceArr addObject:model];
                }
            }
            [SVProgressHUD dismiss];
        }else{
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:response[@"msg"]];
        }
        
        [self.findTreeTableV reloadData];
    } failure:^(NSError *error) {
        NSLog(@"===%@",error);
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"网络错误,请稍候再试"];
    }];
}

#pragma mark - 处理展开收起逻辑
/**
 在指定位置插入要展示的数据
 @param dataArray 数据数组
 @param row    需要插入的数组下标
 */
- (void)addObjectWithDataArray:(NSMutableArray *)dataArray row:(NSInteger)row {
    for (int i = 0; i < dataArray.count; i++) {
        TKYFindTreeModel *model = dataArray[i];
        model.isOpen = NO;
        [_dataSourceArr insertObject:model atIndex:row];
        row += 1;
    }
}

/**
 删除要收起的数据
 @param dataArray 数据
 @param count   统计删除数据的个数
 @return 删除数据的个数
 */
- (CGFloat)deleteObjectWithDataArray:(NSMutableArray *)dataArray count:(NSInteger)count {
    for (TKYFindTreeModel *model in dataArray) {
        count += 1;
        
        if (model.isOpen && model.isParent == YES) {
            count = [self deleteObjectWithDataArray:model.detailArray count:count];
        }
        
        model.isOpen = NO;
        
        [_dataSourceArr removeObject:model];
    }
    
    return count;
}

/**
 与点击同一层的数据比较，然后删除要收起的数据和插入要展开的数据
 @param model 点击的cell对应的model
 @param row  点击的在tableview的indexPath.row,也对应_resultArray的下标
 */
- (void)compareSameLevelWithModel:(TKYFindTreeModel *)model row:(NSInteger)row {
    NSInteger count = 0;
    NSInteger index = 0;  //需要收起的起始位置
    //如果直接用_resultArray，在for循环为完成之前，_resultArray会发生改变，使程序崩溃。
    NSMutableArray *copyArray = [_dataSourceArr mutableCopy];
    
    for (int i = 0; i < copyArray.count; i++) {
        TKYFindTreeModel *openModel = copyArray[i];
        if (openModel.lv == model.lv) {
            //同一个层次的比较
            if (openModel.isOpen) {
                //删除openModel所有的下一层
                count = [self deleteObjectWithDataArray:openModel.detailArray count:count];
                index = i;
                openModel.isOpen = NO;
                break;
            }
        }
    }
    
    //插入的位置在删除的位置的后面，则需要减去删除的数量。
    if (row > index && row > count) {
        row -= count;
    }
    
    self.findTreeModel = model;
    self.row = row;
    [self requestDataWithID:model.ids];
}

- (void)tapBgViewEvent {
    
    if (self.touchBgView) {
        self.touchBgView();
    }
}
- (IBAction)tureButtonClick:(UIButton *)sender {
    NSLog(@"确定按钮");
    if (self.selectedfindTreeModelBlock) {
        self.selectedfindTreeModelBlock(self.findTreeModel);
    }
}
- (IBAction)cancelButtonClick:(UIButton *)sender {
    NSLog(@"取消按钮");
}

#pragma mark - Gesture Delegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:self.choseView])  return NO;
    return YES;
}

@end
